<?php
/**
 *
 *
 * @since 05.01.2012
 * @author Akulov Denis
 */
abstract class K_MVC_Model_Base {

    /**
     * @var K_Config
     */
    private $_objConfig = null;


    /**
     * @var K_Container
     */
    private $_objDbContainer = null;


    /**
     * @var K_GlobalContext
     */
    private $_gc = null;


    /**
     * @var K_MVC_Model_Factory
     */
    private $_factoryModel = null;


    public function __construct(K_MVC_Model_Factory $factoryModels, array $params, K_Config $objConfig, K_Container $objDbContainer, K_GlobalContext $gc = null) {
        $this->_objConfig = $objConfig;
        $this->_objDbContainer = $objDbContainer;
        $this->_gc = $gc;

        if (empty($params)) {
            return ;
        }

        if (!method_exists($this, '_init')) {
            $this->_throwDbException('Method _init() not found in class', get_class($this));
        }

        $this->_init($params);
    }


    /**
     * @return K_GlobalContext
     */
    protected function _getGc () {
        return $this->_gc;
    }


    /**
     * @return K_Config
     */
    protected function _getConfig () {
        return $this->_objConfig;
    }


    /**
     * @param string $strDbName
     * @param string $strCharset
     * @return DbSimple_Generic_Database
     */
    protected function _getDb($alias) {
        if ($this->_objDbContainer->isEmpty()) {
            // Подключаем файл библиотеки DbSimple
            require_once PATH_LIBRARY.'/php/DbSimple/lib/DbSimple/Mysql.php';
        }

        // Определяем имя подключения
        $connectionName = $this->_getConfig()->getAttribute('DB_ALIAS', $alias);

        if (!$this->_objDbContainer->isExists($connectionName)) {
            $db = DbSimple_Generic::connect(
                $this->_getConfig()->getAttribute('DB_CONNECTIONS', $connectionName)
            );

            $db->query('SET NAMES "utf8"');

            $db->setErrorHandler(array($this, 'throwDbException'));

            $this->_objDbContainer->set($connectionName, $db);
        }

        return $this->_objDbContainer->get($connectionName);
    }


    protected function _createModel($modelName, array $params = array()) {
        return $this->_factoryModel->factory($modelName, $params);
    }


    /**
    * @param string $modelName
    * @return K_MVC_Model_Base
    */
    protected function _getInstanceModel ($modelName, array $params = array()) {
        if (!$this->_gc->isExists($modelName)) {
            $this->_getGc()->set($modelName, $this->_createModel($modelName, $params));
        }

        return $this->_getGc()->get($modelName);
    }



    protected function _throwDbException ($message, $info) {
        throw new Exception($message.': '.$info);
    }

}